package com.ndkj.blog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @program: Blog
 * @description:
 * @author: liuyong
 * @create: 2021-12-28 17:36
 **/
@Component
@Slf4j
public class LogWriterUtils {

    private static File localFile = new File("");
    private static String path = localFile.getAbsolutePath() + "/logs";
    private static File filePath = new File(path);
    private static File file = new File(path + "/log.out");
    private static FileOutputStream fileOutputStream;

    static {
        try {
            if (!filePath.exists()) {
                filePath.mkdirs();
                log.info("文件" + path + "/log.out创建成功");
            }
            if (!file.exists()) {
                file.createNewFile();
                log.info("文件" + path + "/log.out创建成功");
            }

            fileOutputStream = new FileOutputStream(file, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void write(String str) throws IOException {
        fileOutputStream.write((str + "\n").getBytes(StandardCharsets.UTF_8));
    }

    public void close() throws IOException {
        fileOutputStream.close();
    }

}
